package com.myGisChannel.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.myGis.entities.Layer;
import com.myGis.entities.Project;
import com.myGis.entities.User;
import com.myGis.services.IMyGisHelpersServices;
import com.myGis.services.IMyGisServices;
import com.myGis.services.MyGisHelpersServices;
import com.myGis.services.MyGisServer;
import com.myGisChannel.utils.BuildFormUtils;

public class LoadProjectInfoController extends MultiActionController {
	
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *  Este metodo se llama manualmente y la idea es poder probar la funcionalidad de construccion de form dinamico
	 */
	public ModelAndView myGisFormInformation(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
				return new ModelAndView("/customForm");
		
	}
	
	public ModelAndView myGisUploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("Test UpLoadFile");
		Object fileObject = request.getAttribute("file");
        FileItem fileItem = (FileItem) fileObject;
        
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

		return new ModelAndView("/customForm");
	}
	/**
	 * Este metodo prepara toda la informacion de un proyecto para ser mostrada en pantalla.
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadProjectInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView("/loadProjectInfo");
		String param= request.getParameter("idProject");
		User usuario = (User) request.getSession(true).getAttribute("user");
		Project proyecto = getProyecto(usuario.getProjects(),param);
		mav.addObject("long", proyecto.getLongitudeInitial());
		mav.addObject("lat", proyecto.getLatitudeInitial());

		IMyGisServices myGisServices = MyGisServer.getInstance();
		List<Layer> layers = proyecto.getLayers();
		Map<String,String> mp=new HashMap<String, String>();
		Map<String,Object> mpLayersCustom = new HashMap<String, Object>();

		IMyGisHelpersServices imgsh = new MyGisHelpersServices();
		JSONArray jsonArrayExternal= new JSONArray();
		JSONArray jsonArrayCustom= new JSONArray();
		for(Layer layer:layers){
			if("BA".equals(layer.getLayerType())){
				JSONObject data = new JSONObject();
				data.put("nameLayerkey", layer.getName());
				data.put("layerKml",  myGisServices.getKml(layer));
				jsonArrayExternal.put(data);
				//mp.put(layer.getName(), "'" + myGisServices.getKml(layer) + "'");
			}else{
				JSONObject data = new JSONObject();
				data.put("idLayerDB", layer.getLayerId());
				data.put("nameLayerkey", layer.getName());
				data.put("marker",layer.getMarker());
				data.put("layerCustom",  imgsh.layerCustomToJSon(layer));
				JSONArray jform = BuildFormUtils.getCustomForm(layer.getSimpleFields());
				data.put("layerForm", jform.toString());
				jsonArrayCustom.put(data);
				//mpLayersCustom.put(layer.getName(), imgsh.layerCustomToJSon(layer) );
			}
		}
		mav.addObject("externalLayer",jsonArrayExternal);
		mav.addObject("customLayer",jsonArrayCustom);

		
		return mav;
	}


	private Project getProyecto(List proyectos,String param) {
		Iterator<Project> iProyectos = proyectos.iterator();
		while (iProyectos.hasNext()) {
			Project proyecto = (Project) iProyectos.next();
			if(param.equals(proyecto.getProjectId().toString()))
				return proyecto;
			
		}
		return null;
	}

	public ModelAndView paraJose(HttpServletRequest request, HttpServletResponse response){
		String test= request.getParameter("featureToSend");
		String test2= request.getParameter("infoAdicional");
		ModelAndView mav = new ModelAndView("/testAjax");
		mav.addObject("featureToSend", test);
		return mav;
 	}
}
